﻿using AutoMapper;
using Basic.Traceability.Domain.Products;
using Basic.Traceability.ErrorCode;
using Basic.Traceability.Host.Api.Write.Application.Command.Products.TraceableProducts;
using Basic.Traceability.Intrestructrue.Base;
using MediatR;

namespace Basic.Traceability.Host.Api.Write.Application.Handler.Products.TraceableProducts
{
    public class UpdateTraceableProductsHandler : IRequestHandler<UpdateTraceableProductsCommand, APIResult<int>>
    {
        private readonly IBaseRepository<TraceableProductsModel> traceProductsRepository;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateTraceableProductsHandler> logger;

        public UpdateTraceableProductsHandler(IBaseRepository<TraceableProductsModel> traceProductsRepository, IMapper mapper, ILogger<UpdateTraceableProductsHandler> logger)
        {
            this.traceProductsRepository = traceProductsRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 更新商品信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(UpdateTraceableProductsCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var model = traceProductsRepository.GetModel(request.Id);
            if (model != null)
            {
                // 使用AutoMapper将请求映射到现有实体上，而不是创建新实体
                mapper.Map(request, model);
                
                var r = traceProductsRepository.Update(model);
                if(r>0)
                {
                    res.Data = 1;
                    res.Msg = "更新商品信息成功";
                    res.Code = APIEnums.Success;
                    logger.LogInformation("更新商品信息成功");

                }
                else
                {
                    res.Data = 0;
                    res.Msg = "更新商品信息失败";
                    res.Code = APIEnums.Fail;
                    logger.LogError("更新商品信息失败");
                }
            }
            else
            {
                res.Data = 0;
                res.Msg = "商品信息不存在";
                res.Code = APIEnums.Fail;
                logger.LogError("商品信息不存在");
            }
            return Task.FromResult(res);
        }
    }
}
